/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.ufjf.posjava.cm.controller.action.profissional;

import br.ufjf.posjava.cm.model.DAO.ProfissionalDAO;
import br.ufjf.posjava.cm.model.Profissional;
import br.ufjf.posjava.cm.util.ClinicaMorpheusException;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Filipe
 */
@WebServlet(name = "GravaProfissionalAction", urlPatterns = {"/GravaProfissionalAction"})
public class GravaProfissionalAction extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        
        String idProfissional = request.getParameter("idProfissional");
        String nome = request.getParameter("cpNome");
        String funcao = request.getParameter("itemFuncao");
        String usuario = request.getParameter("cpUsuario");
        String senha = request.getParameter("cpSenha");
        String btn = request.getParameter("btn");
        Profissional profissional;
        
        if (btn.equalsIgnoreCase("Gravar")) {
            profissional = new Profissional(0, nome, funcao, usuario, senha);
            
            try {
                //Este método está aqui logo abaixo
                if (validar(profissional)) {
                    new ProfissionalDAO().inserir(profissional);
                }
                
                request.setAttribute("msg", "Profissional salvo com sucesso!");
                RequestDispatcher rd = request.getRequestDispatcher("ListarProfissionalAction");
                rd.forward(request, response);
                
            } catch (ClinicaMorpheusException ex) {  //Minha Exceçao              
                RequestDispatcher rd = request.getRequestDispatcher("NovoProfissionalAction");
                request.setAttribute("msg", ex.getMessage());
                rd.forward(request, response);
            } catch (ClassNotFoundException ex) {
                RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
                request.setAttribute("msg", ex.getMessage());
                request.setAttribute("pag", "erro.jsp");
                rd.forward(request, response);
            } catch (SQLException ex) {
                RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
                request.setAttribute("msg", ex.getMessage());
                request.setAttribute("pag", "erro.jsp");
                rd.forward(request, response);
            }
            
        } else if (btn.equalsIgnoreCase("Alterar")) {
            profissional = new Profissional(new Integer(idProfissional), nome, funcao, usuario, senha);
            
            try {
                if (validar(profissional)) {
                    new ProfissionalDAO().alterar(profissional);
                }                
                request.setAttribute("msg", "Profissional alterado com sucesso!");
                RequestDispatcher rd = request.getRequestDispatcher("ListarProfissionalAction");
                rd.forward(request, response);
                
            } catch (ClinicaMorpheusException ex) {  //Minha Exceçao              
                RequestDispatcher rd = request.getRequestDispatcher("AlteraProfissionalAction");
                request.setAttribute("msg", ex.getMessage());
                rd.forward(request, response);
            } catch (ClassNotFoundException ex) {
                RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
                request.setAttribute("msg", ex.getMessage());
                request.setAttribute("pag", "erro.jsp");
                rd.forward(request, response);
            } catch (SQLException ex) {
                RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
                request.setAttribute("msg", ex.getMessage());
                request.setAttribute("pag", "erro.jsp");
                rd.forward(request, response);
            }
        } else {
            //Esta é a função do botão 'Voltar'
            RequestDispatcher rd = request.getRequestDispatcher("ListarProfissionalAction");
            rd.forward(request, response);
        }
        
    }
    
    private boolean validar(Profissional profissional) throws ClinicaMorpheusException {
        if (profissional.getNome() == null || profissional.getNome().trim().equals("")) {
            throw new ClinicaMorpheusException("O nome do profissional é obrigatório.");
        }
        if (profissional.getUsuario() == null || profissional.getUsuario().trim().equals("")) {
            throw new ClinicaMorpheusException("O usuário deve ser informado.");
        }
        if (profissional.getSenha() == null || profissional.getSenha().trim().equals("")) {
            throw new ClinicaMorpheusException("A senha deve ser informada.");
        }
        return true;
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
